<?php

namespace app\utils\seo;

class Sitemap
{
    /**
     * 获取txt站点内容
     * @param $data
     * @return string
     */
    public static function getTxtData($data){
        $txt="";
        if($data){
            foreach($data as $val){
                $loc=$val["loc"];
                $txt.=$loc."\n";
            }
        }
        return $txt;
    }

    /**
     * 获取html站点内容
     * @param $data
     * @return string
     */
    public static function getHtmlData($file,$data){
        $html="";
        if($file && $data){
            $result=array();
            $result["htmlData"]=$data;
            $html=ob_template($file,$result);
        }
        return $html;
    }

    /**
     * 获取xml站点内容
     * @param $data
     * @return string
     */
    public static function getXmlData($data,$wrap=1){
        $xml=self::xmlHeader();
        if($data){
            foreach($data as $val){
                $loc=$val["loc"];
                $changefreq=isset($val["changefreq"])?$val["changefreq"]:null;
                $lastmod=isset($val["lastmod"])?$val["lastmod"]:null;
                $priority=isset($val["priority"])?$val["priority"]:null;
                $xml.=self::getXml($loc,$changefreq,$lastmod,$priority);
            }
        }
        $xml.=self::xmlFooter();
        if($wrap){
            $xml=self::wrap($xml);
        }
        return $xml;
    }

    /**
     * 内容换行
     * @param $data
     * @return mixed
     */
    public static function wrap($data){
        return  str_replace('><', ">\n<", $data);
    }

    /**
     * 格式化url
     * @param $linkurl
     * @return mixed
     */
    public static function xml_linkurl($linkurl) {
        $search=array(
            "'",
            "&",
            "\"",
            ">",
            "<",
        );
        $replace=array(
            "&apos;",
            "&amp;",
            "&quot;",
            "&gt;",
            "&lt;",
        );
        return str_replace($search, $replace, $linkurl);
    }

    /**
     * xml 内容
     * @param $data
     * @return string
     */
    public static function getXml($loc,$changefreq=null,$lastmod=null,$priority=null){
        $xml="<url>";
        $xml .= '<loc>'.self::xml_linkurl($loc).'</loc>';
        if($lastmod){
            $xml .= '<lastmod>'.$lastmod.'</lastmod>';
        }
        if($changefreq){
            $xml .= '<changefreq>'.$changefreq.'</changefreq>';
        }
        if($priority){
            $xml .= '<priority>'.$priority.'</priority>';
        }
        $xml.="</url>";
        return $xml;
    }

    public static function xmlHeader(){
        $header='<?xml version="1.0" encoding="UTF-8"?>';
        $header.='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        return $header;
    }

    /**
     * 获取尾部
     * @return string
     */
    public static function xmlFooter(){
        return "</urlset>";
    }
}